//
//  UserRegisterVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/5/21.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "UserRegisterVC.h"

@interface UserRegisterVC () {
    NSString *mType;
    int count;
}

@property(weak, nonatomic) IBOutlet UIButton *backBt;
@property(weak, nonatomic) IBOutlet UILabel *titleLb;

@property(weak, nonatomic) IBOutlet UIView *phoneView;
@property(weak, nonatomic) IBOutlet UIView *pwdView;
@property(weak, nonatomic) IBOutlet UIView *confirmView;
@property(weak, nonatomic) IBOutlet UIView *codeView;
@property(weak, nonatomic) IBOutlet UITextField *phoneTf;
@property(weak, nonatomic) IBOutlet UITextField *pwdTf;
@property(weak, nonatomic) IBOutlet UITextField *confirmTf;
@property(weak, nonatomic) IBOutlet UITextField *codeTf;

@property(weak, nonatomic) IBOutlet UIButton *codeBt;
@property(weak, nonatomic) IBOutlet UIButton *regBt;
@property(weak, nonatomic) IBOutlet UIButton *protocolBt;

@end

@implementation UserRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addGesture];
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.phoneTf resignFirstResponder];
    [self.pwdTf resignFirstResponder];
    [self.confirmTf resignFirstResponder];
    [self.codeTf resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setType:(NSString *)type {
    mType = type;
}

- (void)initView {
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    self.titleLb.text = mType;
    [self.regBt setTitle:[mType isEqualToString:@"注册"]?@"立即注册":@"提交" forState:UIControlStateNormal];
    self.phoneView.layer.cornerRadius = 20;
    self.pwdView.layer.cornerRadius = 20;
    self.confirmView.layer.cornerRadius = 20;
    self.codeView.layer.cornerRadius = 20;
    self.codeBt.layer.cornerRadius = 20;
    self.regBt.layer.cornerRadius = 20;
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [[self.codeBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.phoneTf resignFirstResponder];
        NSString *phone = self.phoneTf.text;
        if (phone.length <=0) {
            [JPToast showText:@"手机号不能为空"];
            return;
        }
        if (!isValidMobile(phone)) {
            [JPToast showText:@"请输入正确的手机号码"];
            return;
        }
        [self.codeBt setEnabled:NO];
        if ([self->mType isEqualToString:@"注册"]) {
            [self regSms:phone];
        } else {
            [self updatePwdSms:phone];
        }
    }];
    
    [[self.regBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.phoneTf resignFirstResponder];
        [self.pwdTf resignFirstResponder];
        [self.confirmTf resignFirstResponder];
        [self.codeTf resignFirstResponder];
        NSString *phone = self.phoneTf.text;
        NSString *pwd = self.pwdTf.text;
        NSString *confirm = self.confirmTf.text;
        NSString *code = self.codeTf.text;
        if (phone.length<=0) {
            [JPToast showText:@"请输入手机号码"];
            return;
        }
        if (!isValidMobile(phone)) {
            [JPToast showText:@"请输入正确的手机号码"];
            return;
        }
        if (pwd.length<=0) {
            [JPToast showText:@"请输入密码"];
            return;
        }
        if (pwd.length<6 || pwd.length>30) {
            [JPToast showText:@"请输入正确的密码"];
            return;
        }
        if (![pwd isEqualToString:confirm]) {
            [JPToast showText:@"两次输入的密码不一致"];
            return;
        }
        if (code.length<=0) {
            [JPToast showText:@"请输入短信验证码"];
            return;
        }
        if ([self->mType isEqualToString:@"注册"]) {
            [self reg:phone pwd:pwd code:code];
        } else {
            [self updatePwd:phone pwd:pwd code:code];
        }
    }];
    [[self.protocolBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        UIViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil] instantiateViewControllerWithIdentifier:@"UserProtocolVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)regSms:(NSString *)phone {
    [self showLoading:@"正在获取验证码"];
    NSDictionary *dic = @{@"phone":phone};
    [[[HttpRequest shareInstance] regSms:dic] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            self->count = 60;
            [self countDown];
            [JPToast showText:x[@"message"]];
        } else {
            NSString *msg = x[@"message"];
            msg = [msg containsString:@"流控Permits"] ? @"您的验证操作过于频繁，请稍后再试" : msg;
            [JPToast showText:msg];
            [self.codeBt setEnabled:YES];
        }
        [self hideLoading];
    } error:^(NSError *error) {
        [self.codeBt setEnabled:YES];
        [JPToast showText:@"网络错误"];
        [self hideLoading];
    }];
}

- (void)updatePwdSms:(NSString *)phone {
    [self showLoading:@"正在获取验证码"];
    NSDictionary *dic = @{@"phone":phone};
    [[[HttpRequest shareInstance] updatePwdSms:dic] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            self->count = 60;
            [self countDown];
            [JPToast showText:x[@"message"]];
        } else {
            [JPToast showText:x[@"message"]];
            [self.codeBt setEnabled:YES];
        }
        [self hideLoading];
    } error:^(NSError *error) {
        [self.codeBt setEnabled:YES];
        [JPToast showText:@"网络错误"];
        [self hideLoading];
    }];
}

- (void)reg:(NSString *)phone pwd:(NSString *)pwd code:(NSString *)code {
    [self showLoading:@"注册中"];
    NSDictionary *dic = @{@"phone":phone, @"password":pwd, @"smsCode":code};
    NSData *chipher = [JPAES random128BitAESKey];
    [[[HttpRequest shareInstance] reg:dic chipher:chipher] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            NSString *data = [JPAES AES128DecryptWithCiphertext:x[@"data"] pwdData:chipher];
            if (data) {
                NSDictionary *dic = string2Json(data);
                [[UserManager shareInstance] setLoginMsg:dic];
                [self.navigationController popToRootViewControllerAnimated:NO];
            } else {
                [JPToast showText:@"数据解析出现错误"];
            }
        } else {
            [JPToast showText:x[@"message"]];
        }
        [self hideLoading];
    } error:^(NSError *error) {
        [JPToast showText:@"网络错误"];
        [self hideLoading];
    }];
}

- (void)updatePwd:(NSString *)phone pwd:(NSString *)pwd code:(NSString *)code {
    [self showLoading:@"正在重置密码"];
    NSDictionary *dic = @{@"phone":phone, @"newPassword":pwd, @"smsCode":code};
    NSData *chipher = [JPAES random128BitAESKey];
    [[[HttpRequest shareInstance] updatePwd:dic chipher:chipher] subscribeNext:^(id x) {
        if ([x[@"code"] intValue] == 200) {
            NSString *data = [JPAES AES128DecryptWithCiphertext:x[@"data"] pwdData:chipher];
            if (data) {
                NSDictionary *dic = string2Json(data);
                [[UserManager shareInstance] setLoginMsg:dic];
                [self.navigationController popToRootViewControllerAnimated:NO];
            } else {
                [JPToast showText:@"数据解析出现错误"];
            }
        } else {
            [JPToast showText:x[@"message"]];
        }
        [self hideLoading];
    } error:^(NSError *error) {
        [self hideLoading];
    }];
}

- (void)countDown {
    if (count<=0) {
        [self.codeBt setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.codeBt setEnabled:YES];
    } else {
        [self.codeBt setTitle:[NSString stringWithFormat:@"%dS",count] forState:UIControlStateNormal];
        [self.codeBt setEnabled:NO];
        count--;
        [self performSelector:@selector(countDown) withObject:nil afterDelay:1];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
